package cn.kgc.houseweb.controller;


import cn.kgc.bean.*;
import cn.kgc.config.AlipayConfig;
import cn.kgc.service.HouseOrderService;
import cn.kgc.service.HouseService;
import cn.kgc.service.LiverService;
import cn.kgc.service.ManageService;
import cn.kgc.utils.OrderNoUtils;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.lang.System;
import java.util.Calendar;
import java.util.Date;
@Controller
@CrossOrigin
public class PayController {
    @Reference
    LiverService liverService;
    public String orderno;
    @RequestMapping("/pay")
    public  void toPay(HttpServletResponse response,Integer properties,String price, String gremark, String contact, Integer houseId, String houseName,Integer uid,String loginName) throws Exception{
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String result = null;
        //商户订单号，商户网站订单系统中唯一订单号，必填
//        String out_trade_no = param.getTradeCode();
        Calendar calendar=null;
        calendar=Calendar.getInstance();
        int year=calendar.get(calendar.YEAR);
        int month=calendar.get(calendar.MONTH)+1;
        int day=calendar.get(calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        int end= (int)((Math.random()*9+1)*100000);

        String endStr=String.valueOf(end);
        String out_trade_no = "MH"+String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second)+endStr;
        //付款金额，必填
//        String total_amount = param.getMoney().toString();
        String total_amount =price;
        //订单名称，必填
//        String subject = param.getSubject();
        String subject = gremark;
        //商品描述，可空
//        String body = param.getRemark();
        Liverorder order =new Liverorder();
        String body=gremark;
        order.setOrderno(out_trade_no);
        order.setDate(new Date());
        order.setHouseid(houseId);
        order.setHousename(houseName);
        order.setRemark(gremark);
        order.setUid(uid);
        order.setUname(contact);
        order.setMoney(Double.parseDouble(price));
        order.setProperties(properties);
        order.setState(0);
        order.setBtoa(loginName);
        liverService.addLiverOrder(order);
        orderno=order.getOrderno();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求

        result = alipayClient.pageExecute(alipayRequest).getBody();
        if (result==null){
            response.getWriter().print("调用支付接口失败");
        }else{
            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            response.getWriter().write(result);//直接将完整的表单html输出到页面
/*            response.getWriter().flush();
            response.getWriter().close();*/
        }
    }
    @RequestMapping("alipay/callback/return_sult")
    @ResponseBody
    public String toIndex(Model model, String out_trade_no, String total_amount, String timestamp){
        Liverorder liverorder = liverService.selectOrderByOrderNo(out_trade_no);
        if (liverorder.getState()==1){
            return "MyHouse提醒您:订单已经支付,请勿重复操作!";
        }else{
            liverorder.setState(1);
            liverService.updateLiverOrderState(liverorder);
            /*修改住户的余额*/
            System.out.println(liverorder.getUid());
            Liver liver = liverService.getLiverById(liverorder.getUid());
            System.out.println(liver.getId());
            double money=Double.parseDouble(total_amount);
            double oldmoney=liver.getMoney();
            liver.setMoney(oldmoney+money);
            liverService.update(liver);
            return "<h1>支付成功</h1><br/>订单编号:"+out_trade_no+"<br/>总金额:"+total_amount+"<br/>"+"交易完成时间:"+timestamp+"<br/>充值对象:"+liver.getName()+"(编号"+liver.getId()+")"+"<br>充值后余额:"+liver.getMoney()+"<br/><a href='http://localhost:8082/user_index.html?On&"+liverorder.getOrderno()+"&p="+liverorder.getBtoa()+"'>点此返回主页</a>";
        }
    }
    /*公寓管理模块调用*/
    @Reference
    HouseOrderService houseOrderService;
    @RequestMapping("/housepay")
    public  void housetoPay(HttpServletResponse response,String price, String gremark,Integer houseId) throws Exception{
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.house_return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String result = null;
        //商户订单号，商户网站订单系统中唯一订单号，必填
//        String out_trade_no = param.getTradeCode();

        String out_trade_no = OrderNoUtils.getOrderNo();
        //付款金额，必填
//        String total_amount = param.getMoney().toString();
        String total_amount =price;
        //订单名称，必填
//        String subject = param.getSubject();
        String subject = gremark;
        //商品描述，可空
//        String body = param.getRemark();
        Houseorder order =new Houseorder();
        String body=gremark;
        order.setOrderno(out_trade_no);
        order.setDate(new Date());
        order.setHouseid(houseId);
        order.setRemark(gremark);
        order.setMoney(Double.parseDouble(price));
        order.setProperties(0);
        order.setState(0);
        houseOrderService.addHouseOrder(order);
        orderno=order.getOrderno();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求

        result = alipayClient.pageExecute(alipayRequest).getBody();
        if (result==null){
            response.getWriter().print("调用支付接口失败");
        }else{
            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            response.getWriter().write(result);//直接将完整的表单html输出到页面
/*            response.getWriter().flush();
            response.getWriter().close();*/
        }
    }
    @Reference
    ManageService manageService;
    @Reference
    HouseService houseService;
    @RequestMapping("/alipay/house_callback/return_sult")
    @ResponseBody
    public String toIndexHouse(Model model, String out_trade_no, String total_amount, String timestamp) {
        PageInfo<Houseorder> pageInfo = houseOrderService.selectHouseOrders(1, 1, 0, out_trade_no, new Date("1988/06/06"), new Date("1988/06/06"));
        Houseorder houseorder = pageInfo.getList().get(0);

        if (houseorder.getState() == 1) {
            return "MyHouse提醒您:订单已经支付,请勿重复操作!";
        } else {
            houseorder.setState(1);
            houseOrderService.update(houseorder);
            /*修改住户的余额*/
            Manage manage = manageService.selectManageForHouse(houseorder.getHouseid());
            House house = houseService.selectById(houseorder.getHouseid());

            System.out.println("公寓充值人编号:" + manage.getId());
            double money = Double.parseDouble(total_amount);
            double oldmoney = manage.getMoney();
            manage.setMoney(oldmoney + money);
            manageService.update(manage);
            return "<h1>支付成功</h1><br/>订单编号:" + out_trade_no + "<br/>总金额:" + total_amount + "<br/>" + "交易完成时间:" + timestamp + "<br/>充值对象:"+house.getHousename()+"管理员"+manage.getUsername() + "(编号" + manage.getId() + ")" + "<br>充值后余额:" + manage.getMoney() + "<br/><a href='http://localhost:8081/house_login.html'>点此重新登录</a>";
        }
    }
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String ex(){
        if (orderno!=null){
            return "<h1 style='color:red'>系统异常!</h1>" +
                    "<h2>系统发生异常,请立即拍照或截图本页面,您充值资金可能无法及时到账,请耐心等待1小时,如若1小时后资金仍未到账,请使用本页面的截图或照片联系系统管理员(邮箱:lgp1022@foxmail.com)</h2><br>" +
                    "<h3 style='color:blue'>防伪编码:RjKill"+OrderNoUtils.getOrderNo()+"</h3><h3>订单编号:"+orderno+"</h3><h4 style='color:orange'>异常发生时间:"+new Date()+"</h4><h4 style='color:red'>Warning!警告:如若刻意伪造本页面进行恶意操作,将依法追究刑事或民事责任!</h4>";
        }else{
            return "Error:错误的充值提交信息";
        }
    }


}
